package orderCus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.Cart;
import common.Customer;
import common.Item;
import common.OrderItem;

public class CartInfoServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		//ログインチェック
		HttpSession session = req.getSession();
		Customer user = (Customer)session.getAttribute("user");
		if(user == null || user.equals("null")) resp.sendRedirect(req.getContextPath() +"/index.jsp");
		else
		{
			req.setCharacterEncoding("UTF-8");
			Cart cart = (Cart)session.getAttribute("cart");
			List<OrderItem> list = cart.getItems();
			ArrayList<Item> err = new ArrayList<Item>();
			StringBuffer msg = new StringBuffer();
			if(list.size() == 0)
			{
				msg.append("カートに商品が入っていません。");
			}
			for(int i = 0; i < list.size(); i++)
			{
				OrderItem oi = list.get(i);
				Item item = Item.find_by_code(oi.getItem_code());
				int total_orders = 0;
				for(int j = i+1; j < list.size(); j++)
				{
					OrderItem oi_oi = list.get(j);
					if(oi.getItem_code().equals(oi_oi.getItem_code()))
					{
						total_orders = oi.getOrders() + oi_oi.getOrders();
					}
				}
				if(item.getStock() < total_orders)
				{
					msg.append(item.getName() + " の合計注文数が在庫数を超えています。\n");
					err.add(item);
				}
			}
			
			String url = "../customer/cart.jsp";
			if(msg == null || msg.length() == 0)
			{
				url = "../customer/register.jsp";
			}
			else
			{
				req.setAttribute("msg", msg.toString());
				req.setAttribute("err", err);
			}
			RequestDispatcher dispatcher = req.getRequestDispatcher(url);
			dispatcher.forward(req, resp);
		}
	}
}
